<?php
/**
 * Created by PhpStorm.
 * User: HanSon
 * Date: 2016/9/2
 * Time: 12:06
 */

namespace App\Service;


use App\Dictionary;
use Cache;
use GuzzleHttp\Client;

class TransitService
{
    
    public $client;

    const URL = 'http://wxbus.gzyyjt.net/wei-bus-app/';

    public function __construct()
    {
        $this->client = new Client();
    }

    public function getInfo($message, $keyword)
    {
        $result = Dictionary::transit($keyword);

        $busId = $result['id'];

        $direction = str_contains($message, '出校') ? 1 - $result['direction'] : $result['direction'];

        $transit = Cache::get('transit_' . $keyword . $direction);

        if(!$transit){
            $stationData = $this->request($this->generateStationUrl($busId, $direction));

            $positionData = $this->request($this->generatePositionUrl($busId, $direction));

            Cache::put('transit_' . $keyword . $direction, [$stationData, $positionData], 0.5);
        }else{
            list($stationData, $positionData) = $transit;
        }


        return [json_decode($stationData, true), json_decode($positionData, true)];
    }

    private function generateStationUrl($busId, $direction)
    {
        return self::URL . sprintf('routeStation/getByRouteAndDirection/%d/%d', $busId, $direction);
    }

    private function generatePositionUrl($busId, $direction)
    {
        return self::URL . sprintf('runBus/getByRouteAndDirection/%d/%d', $busId, $direction);
    }

    public function request($url)
    {
        try{
            $response = $this->client->get($url, [
                'headers' => [
                    'Cookie' => 'realOpenId=stupid; openId=stupid',
                    'Referer' => 'http://wxbus.gzyyjt.net/wei-bus-app/'
                ]
            ]);
        }catch(\Exception $e){
            \WechatService::report('公交查询', $e);
            return false;
        }

        return $response->getBody()->getContents();
    }

}